#include "RCPWM.h"
#include "hardwareDef.h"

uint8_t i_HIGH = 0, i_LOW = 0;//索引号
uint8_t chPin[6] = {pwmPin1, pwmPin2, pwmPin3, pwmPin4, pwmPin5, pwmPin6};
uint16_t outVal[6] = {1500, 1500, 988, 1500, 1500, 1500};
uint16_t outVal2[6] = {1500, 1500, 988, 1500, 1500, 1500};
uint8_t loopTimes = 0;

void INIT_PWM(void)
{
  pinMode(pwmPin1, OUTPUT); pinMode(pwmPin2, OUTPUT);
  pinMode(pwmPin3, OUTPUT); pinMode(pwmPin4, OUTPUT);
  pinMode(pwmPin5, OUTPUT); pinMode(pwmPin6, OUTPUT);
  TCCR1A = 0;//普通模式，事件A、B端口不连
  TCCR1B = 0b10;//普通模式，8分频，溢出上限0xFFFF，PWM的分辨率为0.5μs
  TCCR1C = 0;
  TCNT1 = 52202;//超调TCNT1至57535，这样一周期为4000
  OCR1A = 3000 + 52202;//比较器A设定目标
  OCR1B = 3000 + 52202;//比较器B设定目标
  TIMSK1 = 0b111;//打开溢出事件
}

void PWM_VAL(int32_t in[6])
{
  outVal2[0] = in[0];
  outVal2[1] = in[1];
  outVal2[2] = in[2];
  outVal2[3] = in[3];
  outVal2[4] = in[4];
  outVal2[5] = in[5];
}

ISR(TIMER1_OVF_vect)
{//溢出事件，可以看作为起始事件
  TCNT1 = 52202;//超调TCNT1达到50Hz频率需要的周期
  digitalWrite(chPin[i_HIGH * 2], HIGH);//打开管脚
  digitalWrite(chPin[i_HIGH * 2 + 1], HIGH);//打开管脚
  OCR1A = outVal[i_HIGH * 2] * 2 + 52202;//比较器A设定目标
  OCR1B = outVal[i_HIGH * 2 + 1] * 2 + 52202;//比较器B设定目标
  i_LOW = i_HIGH;
  i_HIGH ++;
  if (i_HIGH >= 3)
  {
    i_HIGH = 0;
    outVal[0] = outVal2[0];
    outVal[1] = outVal2[1];
    outVal[2] = outVal2[2];
    outVal[3] = outVal2[3];
    outVal[4] = outVal2[4];
    outVal[5] = outVal2[5];
    if (loopTimes != 255)
    {
      loopTimes ++;
    }
  }
}

ISR(TIMER1_COMPA_vect)
{//比较器A事件，查看的是奇数数组号
  digitalWrite(chPin[i_LOW * 2], LOW);
}

ISR(TIMER1_COMPB_vect)
{//比较器B事件，与A相同，查看的是偶数数组号
  digitalWrite(chPin[i_LOW * 2 + 1], LOW);
}

uint8_t PWM_UPDATED(void)
{
  uint8_t old = loopTimes;
  loopTimes = 0;
  return old;
}
